package com.gogo.mall.controller;

import com.alibaba.fastjson.JSONObject;
import com.gogo.mall.common.tool.MD5;
import com.gogo.mall.entity.QyMember;
import com.gogo.mall.jwt.UserLoginToken;
import com.gogo.mall.result.ResponseData;
import com.gogo.mall.service.QyMemberService;
import com.gogo.mall.utils.Sms;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
@RequestMapping("index")
@RestController
public class BaseController {
    /**
     * 服务对象
     */
    @Resource
    private QyMemberService qyMemberService;
    private static String code=null;//验证码
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public QyMember selectOne(Integer id) {
        return this.qyMemberService.queryById(id);
    }

    /**
     *
     * 发送短信验证码
     */
    @PostMapping("getSmsCode")
    public ResponseData getSmsCode(@RequestBody String telphone) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(telphone);
        String tel = (String) jsonObject.get("telphone");
        code = Sms.sendSms(tel);
        return new ResponseData("200","发送成功");
    }
    //注册
    @PostMapping("register")
    @Transactional
    public ResponseData register(@RequestBody Map<String,String>map){

        String telphone = map.get("telphone");
        String password = map.get("password");
        String newcode = map.get("code");
        QyMember member = new QyMember();
        member.setTelphone(telphone);
        if(telphone==null ||telphone.equals("")||password==null||password.equals("")){
            return new ResponseData("0","手机号和密码不能为空");
        }
        boolean ok = qyMemberService.checkTel(telphone);
        if (!ok){
            return new ResponseData("0","手机号格式错误");
        }
        boolean b=qyMemberService.queryByTel(member);
        if(!b){
            return new ResponseData("0","手机号已存在！");
        }

        //校验验证码
        if(!code.equals(newcode))
            return new ResponseData("0","验证码错误");

        //md5加密密码
        member.setPassword(MD5.encrypt(password));
        QyMember insert = qyMemberService.insert(member);
        return new ResponseData("200","注册成功");
    }
    //登录
    @PostMapping("login")
    @UserLoginToken
    public ResponseData login(@RequestBody  QyMember memberInfo){
        String telphone = memberInfo.getTelphone();
        String password = memberInfo.getPassword();
        if(telphone==null||telphone.equals("")||password==null||password.equals("")){
            return new ResponseData("0","账号密码不能为空");
        }
        boolean ok = qyMemberService.checkTel(telphone);
        if (!ok){
            return new ResponseData("0","手机号格式错误");
        }
        //数据库查询
        String encrypt = MD5.encrypt(password);
        memberInfo.setPassword(encrypt);
        return qyMemberService.loginCheck(memberInfo);
    }
}
